package com.pig4cloud.pigx.contract.mq.listener;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.pig4cloud.pigx.common.customize.exception.MqNotAckException;
import com.pig4cloud.pigx.common.customize.security.utils.SecurityUtil;
import com.pig4cloud.pigx.common.customize.utils.CommonUtil;
import com.pig4cloud.pigx.contract.constant.ContractMqConstants;
import com.pig4cloud.pigx.contract.entity.ContractPositionMarginDetail;
import com.pig4cloud.pigx.contract.mapper.ContractPositionMarginDetailMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 新增仓位保证金明细队列监听
 *
 * @since 2022/9/12 22:04
 */
@Slf4j
@Component
@AllArgsConstructor
public class PositionMarginDetailNewListener {

	private final ContractPositionMarginDetailMapper contractPositionMarginDetailMapper;
	private final CommonUtil commonUtil;
	private final SecurityUtil securityUtil;

	/**
	 * 监听 contract.position.margin.detail 队列，开始持久化仓位保证金变动明细
	 *
	 * @param detailList detailList
	 * @since 2022/9/16 16:00
	 */
	@RabbitListener(bindings = {
			@QueueBinding(
					value = @Queue(value = ContractMqConstants.QUEUE_FANOUT_CONTRACT_POSITION_MARGIN_DETAIL),
					exchange = @Exchange(value = ContractMqConstants.QUEUE_FANOUT_CONTRACT_POSITION_MARGIN_DETAIL, type = ExchangeTypes.FANOUT)
			)})
	@Transactional(rollbackFor = Throwable.class)
	public void run(List<ContractPositionMarginDetail> detailList) {
		log.info("{} 开始持久化仓位保证金变动明细。msg：{}", this.getClass().getSimpleName(), detailList);

		if (CollectionUtils.isEmpty(detailList)) {
			return;
		}

		// 遍历，初始化
		detailList.forEach(securityUtil::initCreateAbout);

		if (contractPositionMarginDetailMapper.saveBatch(detailList) != detailList.size()) {
			throw new MqNotAckException("持久化仓位保证金变动明细失败");
		}
	}
}
